const express = require('express')
const router = express.Router()
const humps = require('humps')
const db = require('../../database/db')

module.exports = (() => {
    // 订单管理
    router.get('/resourcess', async (req, res, next) => {
        try {
            let sql = ''
            req.query.pick === '未提车' ? sql = 'AND r.`is_pick_car` = 0 ' :
                req.query.pick === '已提车' ? sql = 'AND r.`is_pick_car` = 1 ' : ''
            if (+req.query.depositToAchievement) {
                sql += 'AND r.`deposit_to_achievement` = 1 '
            } else {
                sql += 'AND r.`deposit_to_achievement` = 0 '
            }
            const doc = humps.camelizeKeys(await db.getResourcess({ limit: req.query.limit, offset: req.query.offset, search: req.query.search, sql }))
            const { total } = await db.getResourcessTotal({ search: req.query.search, sql })
            const temp = []
            const promises = []
            doc.forEach(item => {
                const promise = new Promise(async resolve => {
                    const cancellation = item.cancellation ? await db.getCancellationById(item.cancellation) : item.cancellation
                    item.cancellation = cancellation ? cancellation.name : ''
                    item.mfrFinance = item.mfrFinance ? '是' : ''
                    temp.push(item)
                    resolve(temp)
                })
                promises.push(promise)
            })
            Promise.all(promises).then((data) => {
                res.send({
                    doc,
                    total
                })
            })
        } catch (err) {
            next(err)
        }
    })

    router.put('/editResources/:id', async (req, res, next) => {
        try {
            let existResources = await db.getResourcesById(req.params.id)
            if (!existResources) {
                res.json({
                    status: 0,
                    msg: '该订单不存在！'
                })
                return
            }
            const cancellation = await db.getCancellationByName(req.body.cancellation)
            const data = {
                id: req.params.id,
                is_ordertaking: req.body.ordertaking ? 1 : 0,
                cartype: req.body.cartype ? req.body.cartype : '',
                cancellation_id: cancellation ? cancellation.id : 0,
                is_pick_car: req.body.pickcar ? 1 : 0,
                mfr_finance: req.body.mfrFinance ? 1 : 0,
                pick_car_time: req.body.pickcartime ? req.body.pickcartime : ''
            }
            const success = await db.updateResources(data) // 更新订单表数据

            if (success) {
                res.json({
                    status: 1,
                    msg: 'ok'
                })
            }
        } catch (err) {
            next(err)
        }
    })

    return router
})();